﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Module.Core.LoginSystem.Commons;
using Module.Core.LoginSystem.Commons.Framwork;
using Module.Core.LoginSystem.Commons.Utilities;
using Module.Core.LoginSystem.Components.Commands;
using Module.Core.LoginSystem.Components.Roles;
using Module.Core.LoginSystem.Components.Users;

namespace Web.Cms.Users
{
    public partial class UserRole : AdminUserControl
    {
        private int _userId;
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            CommandInfo _commandInfo = CommandController.GetCommand("admin_usermanager");
            RolePermisionInfo _roleInfo =
                    RoleController.GetReadWritePermison(CurrentUser.UserID, _commandInfo.CommandID);
            if (_roleInfo == null) return;
            if (_roleInfo.Write == 0)
            {
                btnUpdate.Visible = false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _userId = ConvertUtility.ToInt32(Request.QueryString["userinroleid"]);
            lblUpdateStatus.Text = string.Empty;
            if (Page.IsPostBack) return;
            UserInfo _user = UserController.GetUser(_userId);
            if (_user != null)
            {
                lblUser.Text = _user.Username;
                List<RoleInfo> _lstRoles = RoleController.GetRoles(CurrentPortalID);
                lstRoles.DataSource = _lstRoles;
                lstRoles.DataBind();
                List<RoleInfo> _lstRolesOfUser = RoleController.GetRoles(CurrentPortalID, _userId);
                foreach (RoleInfo _role in _lstRolesOfUser)
                {
                    ListItem _item = lstRoles.Items.FindByValue(_role.RoleID.ToString());
                    if (_item != null) _item.Selected = true;
                }
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (ListItem _item in lstRoles.Items)
                {
                    if (_item.Selected)
                        UserController.AddUserToRole(_userId, ConvertUtility.ToInt32(_item.Value));
                    else
                        UserController.RemoveUserFromRole(_userId, ConvertUtility.ToInt32(_item.Value));
                }
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
            }
            catch (Exception ex)
            {
                lblUpdateStatus.Text = ex.Message;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(UIProcess.GetCPPage(CurrentPortalID, "admin_usermanager", new string[] { }, new string[] { }));
        }
    }
}